# coding: utf-8


'''
快速检查所有平台API的返回结果:
http://wiki.it.yzs.io:8090/pages/viewpage.action?pageId=31211404
'''
import time
import urllib2
from utils.req import *
from utils.jktest import *
from test_case.usk_resource_data import *


def run_case(api, url, params, output):
    global Result_Map
    ret = send_get(url, params)
    unmatchs = get_unmatch_list(output, ret)
    result = "Pass"
    if unmatchs:
        result = 'Fail'
        print "Fail %s" % api
        print unmatchs
        print ret
        print '-' * 40
    # else:
    #     print "Pass %s" % api
    Result_Map[result].append(api)

def check_resource_api(api=None):
    if api is not None:
        case = USK_RESOURCER[api]
        url = RESOURCE_PATH + api
        params = case["input"]
        output = case["output"]
        run_case(api, url, params, output)
        return 
    for api, case in USK_RESOURCER.items():
        url = RESOURCE_PATH + api
        params = case["input"]
        output = case["output"]
        run_case(api, url, params, output)

def output():
    pass_api = Result_Map["Pass"]
    fail_api = Result_Map["Fail"]
    total = len(pass_api) + len(fail_api)
    print '----------------------------------------------'
    for api in pass_api:
        print 'Pass >> %s' % api
    print '----------------------'
    for api in fail_api:
        print 'Fail >> %s' % api
    print '----------------------------------------------'
    print "Total: %d, Pass: %d Fail: %d" % (total, len(pass_api), len(fail_api))

def perf_test():
    tid = '0'
    log = 'log.log'
    duration = 3

    if len(sys.argv) >= 3:
        tid = sys.argv[1]
        duration = int(sys.argv[2])
    if len(sys.argv) >= 4:
        log = sys.argv[3]

    pass_ = 0
    total = 0

    print "thread %s will run %s(s)" % (tid, duration)
    begin = time.time()
    while time.time() < begin + duration:
        ret = get_weather_forecast()

        if '"errorCode":"0"' in ret:
            pass_ += 1
        total += 1

    dur = (time.time() - begin)
    tps = pass_ / dur
    reps_time = dur / pass_
    result = '\nthread: %s: total: %d, pass_: %d, TPS: %.2f, reps_time: %.4f, elapsed_time: %.2f\n' %(tid, total, pass_, tps, reps_time, dur)
    print result.strip()
    with open(log, 'a') as log:
        log.write(result)


if __name__ == '__main__':
    Result_Map = {"Pass" : [], "Fail" : []}
    # IT = "IT-DEFAULT"
    # VI ="VI-DEFAULT"
    # VD = "VD-DEFAULT"
    # LH = "LH-DEFAULT"
    # WEB = "WEB-DEFAULT"
    # templateCode = IT

    Server = 'test-uat-skill-resource.hivoice.cn' # UAT
    # Server = 'usk-resource.hivoice.cn' # Production
    # Server = '192.168.3.244:8082'

    RESOURCE_PATH = 'http://%s/unios-usk-resource/rest/v1/' % Server
    # RESOURCE_PATH = 'https://
    api = None
    # api = "content/get_content"
    # api = "faq/get_answer"
    # api = "faq/get_answer_list"
    check_resource_api(api)
    output()
